from django.shortcuts import render
import threading
import random, string
from utrgen_app.utrgen_utils.workflow import preprocessing_seq, output_result
import pandas as pd
import os


class TaskThread(threading.Thread):  # 定义多线程
    def __init__(self, func, args):
        super().__init__()
        self.result = None
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        return self.result


task_thread = None
task_num = ''
seq_fst = ''
seq_num = 0
purpose = None
res_df = None
generate_utr = False


# Create your views here.


def homepage(request):
    return render(request, 'homepage.html')


def startAnalysis(request):
    return render(request, 'analysis.html')


def download(request):
    return render(request, 'download.html')


def about(request):
    return render(request, 'about.html')


def preprocess(request):
    global task_num, seq_fst, purpose, seq_num, res_df, task_thread, generate_utr
    task_num = ''
    seq_fst = ''
    purpose = None
    program_type = None
    res_df = None
    generate_utr = False
    try:
        if request.method == 'POST':
            task_num = ''.join(random.sample(string.ascii_letters + string.digits, 6))
            seq_fst = request.POST['seq_fst']
            seq_lst, name_lst = preprocessing_seq(seq_fst)
            seq_num = len(name_lst)
            purpose = request.POST.get('purpose')
            if purpose == 'generate':
                generate_utr = True
            task_thread = TaskThread(output_result, args=(seq_fst, generate_utr, task_num))
            task_thread.start()
            temp_dict = {'task_num': task_num, 'seq_num': seq_num, 'program_type': program_type}
            return render(request, 'preprocess.html', temp_dict)
    except:
        return render(request, 'error.html')


def process(request, task_num):
    temp_dict = {'task_num': task_num, 'seq_fst': seq_fst, 'purpose': purpose}
    return render(request, 'process.html', temp_dict)


def results(request, task_num):
    global res_df
    if os.path.exists('utrgen_app/static/output/{}_report.xlsx'.format(task_num)):
        res_df = pd.read_excel('utrgen_app/static/output/{}_report.xlsx'.format(task_num))
        res_html = res_df.to_html(index=False).replace('<table', '<table data-toggle="table"').replace('<th>', '<th data-sortable="true">')
        res_dict = {'task_num': task_num, 'seq_fst': seq_fst, 'purpose': purpose, 'res_html': res_html}
        return render(request, 'results.html', res_dict)
    else:
        return process(request, task_num)

# Create your views here.
